import { Component, OnInit, OnDestroy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule, FormGroup, FormBuilder, Validators } from '@angular/forms';
import { ListService, PagedResultDto } from '@abp/ng.core';
import { ThemeSharedModule } from '@abp/ng.theme.shared';
import { CarInventryService } from './carinventry.service';
import { CarInventryDto, CreateUpdateCarInventryDto } from './models';
import { ConfirmationService, Confirmation } from '@abp/ng.theme.shared';
import { ToasterService } from '@abp/ng.theme.shared';
import { Subscription } from 'rxjs';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { finalize } from 'rxjs/operators';

@Component({
  selector: 'app-car-inventry',
  standalone: true,
  imports: [CommonModule, FormsModule, ReactiveFormsModule, ThemeSharedModule],
  templateUrl: './carinventry.component.html',
  styleUrl: './carinventry.component.scss',
  providers: [ListService]
})
export class CarInventryComponent implements OnInit, OnDestroy {
  carInventry = { items: [], totalCount: 0 } as PagedResultDto<CarInventryDto>;
  createCarInventryForm: FormGroup;
  isModalOpen = false;
  isEditMode = false;
  selectedCarInventryId: string;
  isSaving = false;
  Math = Math;

  selectedItems: string[] = [];
  isAllSelected = false;

  pageSizeOptions = [10, 20, 30, 50];
  currentPageSize = 10;
  maxPageCount = 1;
  visiblePageNumbers: number[] = [];
  inputPageNumber: number = 1;

  private subscription: Subscription = new Subscription();

  searchKeyword = '';
  isSearchMode = false;
  isLoading = false;

  constructor(
    public readonly list: ListService,
    private carInventryService: CarInventryService,
    private fb: FormBuilder,
    private confirmation: ConfirmationService,
    private toaster: ToasterService,
    private modalService: NgbModal
  ) {
    this.createCarInventryForm = this.fb.group({
      FleetcarId: [null],
      VehicleId: [null],
      VehicleName: ['', Validators.maxLength(50)],
      VehicleNumber: ['', Validators.maxLength(50)],
      Shipper: ['', Validators.maxLength(50)],
      ShipperAddress: ['', Validators.maxLength(200)],
      Consignee: ['', Validators.maxLength(50)],
      ConsigneeAddress: ['', Validators.maxLength(200)],
      Goods: ['', Validators.maxLength(50)],
      PieceCount: [null],
      Declaration: ['', Validators.maxLength(50)],
      CubicMeterss: [null],
      Weightk: [null],
      Lengthm: [null],
      Widthm: [null],
      Heightm: [null],
      FreightAmount: [null],
      ReturnRequired: ['', Validators.maxLength(50)],
      CustomerNo: [null],
      OrderNo: ['', Validators.maxLength(50)],
      Remarks: ['']
    });
  }

  ngOnInit() {
    this.list.page = 1;
    this.loadData();
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }

  loadData() {
    if (this.list.page <= 0) {
      this.list.page = 1;
    }
    this.isLoading = true;
    const streamCreator = (query) => {
      const params = {
        ...query,
        maxResultCount: this.currentPageSize,
        skipCount: (this.list.page - 1) * this.currentPageSize
      };
      return this.carInventryService.getList(params);
    };
    this.subscription.add(
      this.list.hookToQuery(streamCreator)
        .pipe(finalize(() => {
          this.isLoading = false;
          this.selectedItems = [];
          this.isAllSelected = false;
        }))
        .subscribe((response: PagedResultDto<CarInventryDto>) => {
          this.carInventry = response;
          if (response.totalCount > 0) {
            this.maxPageCount = Math.ceil(response.totalCount / this.currentPageSize);
            if (this.list.page > this.maxPageCount) {
              this.list.page = this.maxPageCount;
              if (response.items.length === 0) {
                this.loadDataWithoutCheck();
              }
            }
          } else {
            this.maxPageCount = 1;
            this.list.page = 1;
          }
          this.updateVisiblePageNumbers();
        }, error => {
          this.toaster.error('加载数据失败，请稍后重试', '错误', { life: 7000 });
        })
    );
  }

  loadDataWithoutCheck() {
    this.isLoading = true;
    const streamCreator = (query) => {
      const params = {
        ...query,
        maxResultCount: this.currentPageSize,
        skipCount: (this.list.page - 1) * this.currentPageSize
      };
      return this.carInventryService.getList(params);
    };
    this.subscription.add(
      this.list.hookToQuery(streamCreator)
        .pipe(finalize(() => {
          this.isLoading = false;
        }))
        .subscribe((response: PagedResultDto<CarInventryDto>) => {
          this.carInventry = response;
          this.updateVisiblePageNumbers();
        }, error => {
          this.toaster.error('加载数据失败，请稍后重试', '错误', { life: 7000 });
        })
    );
  }

  updateVisiblePageNumbers() {
    const currentPage = this.list.page || 1;
    const pageNumbers = [];
    pageNumbers.push(1);
    let startPage = Math.max(2, currentPage - 2);
    let endPage = Math.min(this.maxPageCount - 1, currentPage + 2);
    if (currentPage <= 3) {
      endPage = Math.min(5, this.maxPageCount - 1);
    }
    if (currentPage >= this.maxPageCount - 2) {
      startPage = Math.max(2, this.maxPageCount - 4);
    }
    if (startPage > 2) {
      pageNumbers.push(-1);
    }
    for (let i = startPage; i <= endPage; i++) {
      pageNumbers.push(i);
    }
    if (endPage < this.maxPageCount - 1) {
      pageNumbers.push(-2);
    }
    if (this.maxPageCount > 1) {
      pageNumbers.push(this.maxPageCount);
    }
    this.visiblePageNumbers = pageNumbers;
    this.inputPageNumber = currentPage;
  }

  onPageSizeChange(pageSize: number) {
    this.currentPageSize = pageSize;
    this.list.page = 1;
    this.loadData();
  }

  goToPage(page: number) {
    if (page >= 1 && page <= this.maxPageCount && page !== this.list.page) {
      this.list.page = page;
      this.loadData();
    }
  }

  onPageInputChange(event: Event) {
    const inputElement = event.target as HTMLInputElement;
    const value = inputElement.value.trim();
    let pageNum = parseInt(value, 10);
    if (isNaN(pageNum) || pageNum < 1) {
      pageNum = 1;
    } else if (pageNum > this.maxPageCount) {
      pageNum = this.maxPageCount;
    }
    this.inputPageNumber = pageNum;
  }

  onPageInputKeyUp(event: KeyboardEvent) {
    if (event.key === 'Enter') {
      this.goToPage(this.inputPageNumber);
    }
  }

  openCreateModal() {
    this.isModalOpen = true;
    this.isEditMode = false;
    this.createCarInventryForm.reset();
    this.createCarInventryForm.patchValue({
      FleetcarId: null,
      VehicleId: null,
      VehicleName: '',
      VehicleNumber: '',
      Shipper: '',
      ShipperAddress: '',
      Consignee: '',
      ConsigneeAddress: '',
      Goods: '',
      PieceCount: null,
      Declaration: '',
      CubicMeterss: null,
      Weightk: null,
      Lengthm: null,
      Widthm: null,
      Heightm: null,
      FreightAmount: null,
      ReturnRequired: '',
      CustomerNo: null,
      OrderNo: '',
      Remarks: ''
    });
  }

  openEditModal(carInventryId: string) {
    this.isModalOpen = true;
    this.isEditMode = true;
    this.selectedCarInventryId = carInventryId;
    this.carInventryService.getById(carInventryId).subscribe((data) => {
      this.createCarInventryForm.patchValue({
        FleetcarId: data.FleetcarId,
        VehicleId: data.VehicleId,
        VehicleName: data.VehicleName,
        VehicleNumber: data.VehicleNumber,
        Shipper: data.Shipper,
        ShipperAddress: data.ShipperAddress,
        Consignee: data.Consignee,
        ConsigneeAddress: data.ConsigneeAddress,
        Goods: data.Goods,
        PieceCount: data.PieceCount,
        Declaration: data.Declaration,
        CubicMeterss: data.CubicMeterss,
        Weightk: data.Weightk,
        Lengthm: data.Lengthm,
        Widthm: data.Widthm,
        Heightm: data.Heightm,
        FreightAmount: data.FreightAmount,
        ReturnRequired: data.ReturnRequired,
        CustomerNo: data.CustomerNo,
        OrderNo: data.OrderNo,
        Remarks: data.Remarks
      });
    }, (error) => {
      this.toaster.error('加载车辆信息失败', '错误');
      this.closeModal();
    });
  }

  closeModal() {
    this.isModalOpen = false;
    this.createCarInventryForm.reset();
  }

  save() {
    if (this.createCarInventryForm.invalid) {
      Object.keys(this.createCarInventryForm.controls).forEach(key => {
        const control = this.createCarInventryForm.get(key);
        control.markAsDirty();
        control.markAsTouched();
      });
      this.toaster.warn('请填写必填字段并修正表单错误', '表单校验');
      return;
    }
    const carInventryData = this.createCarInventryForm.value as CreateUpdateCarInventryDto;
    this.isSaving = true;
    if (this.isEditMode) {
      this.carInventryService.update(this.selectedCarInventryId, carInventryData).subscribe(() => {
        this.isModalOpen = false;
        this.createCarInventryForm.reset();
        this.loadData();
        this.isSaving = false;
        this.toaster.success('车辆信息已成功更新', '成功');
      }, (error) => {
        this.isSaving = false;
        this.toaster.error('更新车辆信息失败', '错误');
      });
    } else {
      this.carInventryService.create(carInventryData).subscribe(() => {
        this.isModalOpen = false;
        this.createCarInventryForm.reset();
        this.loadData();
        this.isSaving = false;
        this.toaster.success('车辆信息已成功创建', '成功');
      }, (error) => {
        this.isSaving = false;
        this.toaster.error('创建车辆信息失败', '错误');
      });
    }
  }

  deleteCarInventry(carInventryId: string) {
    this.confirmation.warn('确定要删除此车辆吗？', '删除确认', { messageLocalizationParams: [] })
      .subscribe((status) => {
        if (status === Confirmation.Status.confirm) {
          this.carInventryService.delete(carInventryId).subscribe(() => {
            if (this.carInventry.items.length === 1 && this.list.page > 1) {
              this.list.page--;
            }
            this.loadData();
            this.toaster.success('车辆已成功删除', '成功');
          }, (error) => {
            this.toaster.error('删除车辆失败', '错误');
          });
        }
      });
  }

  selectAll(checked: boolean): void {
    if (checked) {
      this.selectedItems = this.carInventry.items.map(item => item.id);
      this.isAllSelected = true;
    } else {
      this.selectedItems = [];
      this.isAllSelected = false;
    }
  }

  toggleItemSelection(id: string): void {
    const idx = this.selectedItems.indexOf(id);
    if (idx > -1) {
      this.selectedItems.splice(idx, 1);
    } else {
      this.selectedItems.push(id);
    }
    this.isAllSelected = this.selectedItems.length === this.carInventry.items.length;
  }

  deleteSelected(): void {
    if (this.selectedItems.length === 0) {
      this.toaster.info('请先选择要删除的车辆', '提示');
      return;
    }
    this.confirmation.warn('确定要批量删除选中的车辆吗？', '批量删除确认', { messageLocalizationParams: [] })
      .subscribe((status) => {
        if (status === Confirmation.Status.confirm) {
          const deleteObservables = this.selectedItems.map(id => this.carInventryService.delete(id));
          Promise.all(deleteObservables.map(obs => obs.toPromise())).then(() => {
            this.loadData();
            this.toaster.success('批量删除成功', '成功');
          }).catch(() => {
            this.toaster.error('批量删除失败', '错误');
          });
        }
      });
  }
} 